//
//  QCControlViewController.swift
//  爱汽车
//
//  Created by liujianlong on 2023/8/8.
//

import UIKit
import TCCKit
class QCControlViewController: QCViewController {
    private var currentBytes = [UInt8]()
    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
        DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {
            APP.checkAPPUpdate()
        })
    }
//    override func viewWillAppear(_ animated: Bool) {
//        super.viewWillAppear(animated)
//        BLEData.appSetDataToPer(AIQC.userInfo.cmd,"00").write
//    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        BLEData.appSetDataToPer(AIQC.userInfo.cmd,"00").write
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        BLE.stopScan()
    }
    
    override func initUI() {
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(QCSetupTopCell.nib(), forCellReuseIdentifier: QCSetupTopCell.ID())
        tableView.register(QCSetupBottomCell.nib(), forCellReuseIdentifier: QCSetupBottomCell.ID())
        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(kUIStatusBarHeight)
            make.bottom.equalToSuperview().inset(KUITabBarHeight)
        }
    }
    
    override var base_info: [UInt8]{
        didSet{
            if recived == false {
                DispatchQueue.main.asyncAfter(deadline: .now()+0.5, execute: {[weak self] in
                    self?.recived = true
                })
                return}
            currentBytes = base_info
            tableView.reloadData()
        }
    }
    override var bytes: [UInt8]{
        didSet{
            currentBytes = bytes
            tableView.reloadData()
        }
    }
    
    override func initData() {
        super.initData()
        QCTool.requestAboard()
        let filterProductName = productName()
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            BLE.scanWithOther = { peripheral in
                let product = String(format: "%.2X%.2X", peripheral.advertData[1],peripheral.advertData[0])
                return filterProductName.contains(product) || OTAName.contains(peripheral.name ?? "")
            }
            //"02E9D"
            BLE.scanWithServices = [TouchPad_service, Watch_service,Nordic_OTA_service]
            BLE.startScan(result: nil)
        }
    }
    
    ///下半部分按钮事件
    func actionForBottomCell(_ btn:UIButton){
        recived = false
        //CCHud.start("设置中", stopTime: 1)
        switch btn.tag{
        case 200:///一键低趴
            BLEData.appSetDataToPer(AIQC.oneClickLow.cmd, "00").write
        case 201:///调整到指定位置
            BLEData.appSetDataToPer(AIQC.setPrePos.cmd, "01").write
        case 202:
            BLEData.appSetDataToPer(AIQC.setPrePos.cmd, "02").write
        case 203:
            BLEData.appSetDataToPer(AIQC.setPrePos.cmd, "03").write
        case 204:
            BLEData.appSetDataToPer(AIQC.setPrePos.cmd, "04").write
        case 205:///气罐手动打气
            BLEData.appSetDataToPer(AIQC.aeration.cmd, btn.isSelected ? "00" : "01").write
        case 206:///设置预置位保持自动校准
            BLEData.appSetDataToPer(AIQC.setPreAuto.cmd, btn.isSelected ? "01" : "00").write
            //            if btn.isSelected == false{return}
            //            ///6 s后查询0x91，获取使能状态
            //            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(6)) {[weak self] in
            //                self?.initData()
            //            }
            //        case 207:///系统自检开始
            //            BLEData.appSetDataToPer(AIQC.systemCheckStart.cmd, "01").write
        case 208:///开始主动干燥150ms
            BLEData.appSetDataToPer(AIQC.autoDrying.cmd, "1388").write
        case 207,///系统自检开始
            209:///异常
            let vc = QCErrorController()
            push(vc,true)
        default:
            break
        }
    }
}

//MARK: - UITableViewDataSource
extension QCControlViewController : UITableViewDataSource
{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0{
            let cell = tableView.dequeueReusableCell(withIdentifier: QCSetupTopCell.ID()) as! QCSetupTopCell
            cell.setupView.style = .normal(8)
            cell.bytes = currentBytes
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: QCSetupBottomCell.ID()) as! QCSetupBottomCell
            cell.bytes = currentBytes
            cell.block = {[weak self] btn in
                self?.actionForBottomCell(btn)
            }
            return cell
        }
    }
}
//MARK: - UITableViewDelegate
extension QCControlViewController : UITableViewDelegate
{
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0{
            let y = (kUIScreenHeight - KUITabBarHeight - kUIStatusBarHeight - 192)
            QCSetupTopCellH = max(y, 436)
            QCSetupTopCellH = min(QCSetupTopCellH, 536)
            return QCSetupTopCellH
        }
        return 192
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
}
